package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.configure.HSBCSZooKeeperConfigurator;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncAuthCodeForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncPasswordResetForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncRegisterForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.AuthCodeBackVo;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.UIDBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.SysMgtErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.AccessTokenType;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.LoginFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.SendSMSBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerTenantIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.SuggestionAddForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.reward.vo.BrokerIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.SystemBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.BrokerAuthInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.BrokerManagerInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.BrokerManagerList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.BrokerPermissionList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.ConfigurableSystemSetInfoResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.FansInvitationCodeResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.HomePageTitleResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.PaymentOptionInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.BrokerAuthSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.BrokerManagerIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.BrokerManagerSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.FansInvitationCodeForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.HomePageTitleForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.PaymentOptionSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.ShowPersonNumSetForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.CreateAccountForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.CreateAccountBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.YunxinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerManager;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatRoom;
import com.cloudbroker.bcs.platform.dav.middle.entity.Feedback;
import com.cloudbroker.bcs.platform.dav.middle.entity.ManagerPermission;
import com.cloudbroker.bcs.platform.dav.middle.entity.PaymentOption;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entity.WechatShare;
import com.cloudbroker.bcs.platform.dav.middle.entityview.BrokerManagerView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.BrokerPermissionView;
import com.cloudbroker.bcs.platform.dav.middle.extservice.uc.UCenterService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatRoomService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.FeedbackService;
import com.cloudbroker.bcs.platform.dav.middle.service.ManagerPermissionService;
import com.cloudbroker.bcs.platform.dav.middle.service.PaymentOptionService;
import com.cloudbroker.bcs.platform.dav.middle.service.PermissionService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.WechatShareService;
import com.cloudbroker.bcs.platform.dav.middle.util.AccessTokenUtil;

@Service
public class SystemBizServiceImpl implements SystemBizService {
    
    private static final Logger logger = LoggerFactory.getLogger(SystemBizServiceImpl.class);
    
    @Resource
    private BrokerManagerService brokerManagerService;
    @Resource
    private ManagerPermissionService managerPermissionService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private ChatRoomService chatRoomService;
    @Resource
    private WechatShareService wechatShareService;
    @Resource
    private PaymentOptionService paymentOptionService;
    @Resource
    private FeedbackService feedbackService;
    @Resource
    private YunxinT2BizService yunxinT2;
    @Resource
    private CustomerService customerService;
    @Resource
    private UCenterService uCenterService;
    @Resource
    private TenantService tenantService;
    
    private HSBCSZooKeeperConfigurator zooKeeperConfigurator;
    
    private static final String DEFAULT_OPTION = "10,20,50,100,200";
    
    private List<ManagerPermission> getList(Long manager_id, String permission) {
        List<ManagerPermission> list = new ArrayList<ManagerPermission>();
        String[] str = permission.split(",");
        for (int i = 0; i < str.length; i++) {
            ManagerPermission mp = new ManagerPermission();
            mp.setBroker_manager_id(manager_id);
            mp.setPermission_id(Long.parseLong(str[i]));
            mp.setTenant_id(HSBCPSBizDataContext.getTenantId());
            list.add(mp);
        }
        return list;
    }
    
    @Override
    public HSBCPSBackVO funcBrokerManagerSave(BrokerManagerSaveForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String broker_manager_id = param.getBroker_manager_id();
        String manager_name = param.getManager_name();
        String mobile = param.getMobile();
        String password = param.getPassword();
        String permission = param.getPermission();
        String broker_avatar = param.getBroker_avatar();
        //新增
        if (StringUtil.isBlank(broker_manager_id)) {
            if (checkUserName(param.getManager_name())) {
                return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
            }
            if (StringUtil.isBlank(password)) {
                return VOUtil.genErrorResult(ClientErr.PASSWORD_EMPTY, HSBCPSBackVO.class);
            }
            BrokerManager bm = this.brokerManagerService.getByMobile(mobile);
            if (null != bm) {
                return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, HSBCPSBackVO.class);
            } else {
                bm = new BrokerManager();
                
                //注册用户中心
                if (ConfigValues.IsUserCenter()) {
                    Integer tenant_id = HSBCPSBizDataContext.getTenantId();
                    FuncRegisterForm form = new FuncRegisterForm();
                    form.setLogin_account(mobile);
                    form.setAuth_password(MD5Util.encrypt(password));
                    form.setUser_type("2");
                    form.setTenant_id(tenant_id);
                    form.setAlias_name(manager_name);
                    form.setAvatar(broker_avatar);
                    form.setRegister_flag("1");
                    // 增加注册用户中心投顾下面的管理员的branchno取租户级别的branchno by weishuai 2017-02-15
                    if (tenant_id != null) {
                        logger.debug("sys manager add tenantid:" + tenant_id);
                        Tenant tenant = tenantService.get(tenant_id + "");
                        if (tenant != null) {
                            String branch_no = tenant.getBranch_no();
                            logger.debug("sys manager add branch_no:" + branch_no);
                            form.setBranch_no(branch_no);
                        }
                    }
                    form.setMobile(mobile);
                    UIDBackVo vo = uCenterService.funcRegister(form);
                    /*首次注册或已注册，均视为正常*/
                    if (vo != null && vo.getUser_id() != null) {
                        //更新user_id到manager表
                        //Long user_id = vo.getUser_id();
                        bm.setUser_id(vo.getUser_id());
                    } else {
                        return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR,
                                LoginFormBackForm.class);
                    }
                }
                
                bm.setMobile(mobile);
                bm.setBroker_id(broker_id);
                bm.setBroker_flag(0);
                bm.setName(manager_name);
                bm.setBroker_avatar(broker_avatar);
                bm.setPassword(MD5Util.encrypt(password));
                bm.setCreate_time(new Date());
                bm.setDelete_flag(0);
                yunxinReg(bm);
                this.brokerManagerService.save(bm);
                
                //增加权限
                Long manager_id = bm.getBroker_manager_id();
                List<ManagerPermission> list = getList(manager_id, permission);
                this.managerPermissionService.addPermission(list);
            }
        } else {
            //修改
            
            BrokerManager bm = this.brokerManagerService.get(broker_manager_id);
            if (null == bm) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
            }
            if (!bm.getName().equals(param.getManager_name())) {
                if (checkUserName(param.getManager_name())) {
                    return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
                }
            }
            if (bm.getBroker_flag() == 1) {
                return VOUtil.genErrorResult(ClientErr.BROKER_CANNOT_UPDATE, HSBCPSBackVO.class);
            }
            if (bm.getBroker_manager_id().equals(HSBCPSBizDataContext.getClientIdNoException())) {
                return VOUtil.genErrorResult(ClientErr.SELF_CANNOT_UPDATE, HSBCPSBackVO.class);
            }
            BrokerManager bm1 = this.brokerManagerService.getByMobile(mobile);
            if (null != bm1 && !bm1.getBroker_manager_id().equals(Long.parseLong(broker_manager_id))) {
                return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, HSBCPSBackVO.class);
            }
            
            //bm.setMobile(mobile);
            if (!StringUtil.isBlank(password)) {
                
                //暂时不能修改手机号，如果修改密码需要先去用户中心修改密码
                if (ConfigValues.IsUserCenter()) {
                    FuncAuthCodeForm form = new FuncAuthCodeForm();
                    form.setTenant_id(HSBCPSBizDataContext.getTenantId());
                    form.setLogin_account(bm.getMobile());
                    form.setUser_type("2");
                    AuthCodeBackVo vo = uCenterService.funcAuthCodeGet(form);
                    logger.debug("uc-> api: error_on->" + vo.getError_no() + " error_info->" + vo.getError_info());
                    if (VOUtil.isSuccess(vo)) {
                        String auth_check_code = vo.getAuth_code();
                        FuncPasswordResetForm fform = new FuncPasswordResetForm();
                        fform.setAuth_code(auth_check_code);
                        fform.setAuth_password(MD5Util.encrypt(password));
                        form.setUser_type("2");
                        form.setUser_token(param.getUser_token());
                        HSBCPSBackVO hvo = uCenterService.funcPasswordReset(fform);
                        if (!VOUtil.isSuccess(hvo)) {
                            return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR,
                                    HSBCPSBackVO.class);
                        }
                    } else {
                        return VOUtil.genErrorResult(HSBCPSErrorCodes.USER_CENTER_INTERFACE_ERR,
                                SendSMSBackForm.class);
                    }
                }
                
                bm.setPassword(MD5Util.encrypt(password));
            }
            bm.setName(manager_name);
            bm.setBroker_avatar(broker_avatar);
            this.brokerManagerService.update(bm);
            //修改权限
            String[] ids = { broker_manager_id };
            this.managerPermissionService.deleteAll(ids);
            List<ManagerPermission> list = getList(Long.valueOf(broker_manager_id), permission);
            this.managerPermissionService.addPermission(list);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    private BrokerManager yunxinReg(BrokerManager manager) {
        // 调用云信接口
        CreateAccountForm param = new CreateAccountForm();
        param.setAccid(UUID.randomUUID().toString().replace("-", ""));
        param.setName(manager.getName());
        param.setIcon(manager.getBroker_avatar());
        CreateAccountBackVo yunxinMap = yunxinT2.createAccount(param);
        if (yunxinMap == null) {
            return manager;
        }
        String yunxin_token = yunxinMap.getToken();
        manager.setYunxin_token(yunxin_token);
        String yunxin_acct = yunxinMap.getAccid();
        manager.setYunxin_acct(yunxin_acct);
        return manager;
    }
    
    @Override
    public HSBCPSBackVO funcBrokerManagerDel(BrokerManagerIdForm param) {
        String broker_manager_id = param.getBroker_manager_id();
        String[] managerIds = broker_manager_id.split(",");
        for (String managerId : managerIds) {
            BrokerManager bm = this.brokerManagerService.get(managerId);
            if (null == bm) {
                return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
            }
            if (bm.getBroker_flag() != null && bm.getBroker_flag() == 1) {
                return VOUtil.genErrorResultVo(ClientErr.BROKER_CANNOT_DEL);
            }
            if (bm.getBroker_manager_id().equals(HSBCPSBizDataContext.getClientIdNoException())) {
                return VOUtil.genErrorResultVo(ClientErr.SELF_CANNOT_DEL);
            }
        }
        //删除权限
        this.managerPermissionService.deleteAll(managerIds);
        //删除管理员
        this.brokerManagerService.deleteManager(managerIds);
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public BrokerManagerInfoForm funcBrokerManagerInfo(BrokerManagerIdForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String broker_manager_id = param.getBroker_manager_id();
        BrokerManager bm = this.brokerManagerService.get(broker_manager_id);
        BrokerManagerInfoForm form = new BrokerManagerInfoForm();
        if (null == bm) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, BrokerManagerInfoForm.class);
        } else {
            if (!broker_id.equals(bm.getBroker_id())) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, BrokerManagerInfoForm.class);
            }
            form.setMobile(bm.getMobile());
            form.setManager_name(bm.getName());
            form.setBroker_avatar(bm.getBroker_avatar());
            form.setPassword("");
            List<Integer> list = this.managerPermissionService.getByManagerId(broker_manager_id);
            StringBuilder sb = new StringBuilder();
            if (null != list && list.size() > 0) {
                boolean flag = false;
                for (Integer i : list) {
                    if (flag) {
                        sb.append(",");
                    } else {
                        flag = true;
                    }
                    sb.append(i);
                }
            }
            form.setPermission(sb.toString());
        }
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public BrokerManagerList funcBrokerManagerList(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        List<BrokerManagerView> list = this.brokerManagerService.getByBrokerId(broker_id);
        BrokerManagerList bml = new BrokerManagerList();
        if (null != list) {
            bml.newDataList().addAll(list);
        } else {
            bml.newDataList().addAll(new ArrayList<BrokerManagerView>());
        }
        return VOUtil.setSuccessResult(bml);
    }
    
    @Override
    public BrokerPermissionList funcBrokerPermissionList(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        List<BrokerPermissionView> list = this.permissionService.getByBrokerId(broker_id);
        BrokerPermissionList bpl = new BrokerPermissionList();
        if (null != list) {
            bpl.newDataList().addAll(list);
        } else {
            bpl.newDataList().addAll(new ArrayList<BrokerPermissionView>());
        }
        return VOUtil.setSuccessResult(bpl);
    }
    
    @Override
    public BrokerAuthInfoForm funcAuthBroker(HSBCPSVO param) {
        BrokerAuthInfoForm form = new BrokerAuthInfoForm();
        String wx_app_key = ConfigUtil.get("wx.app.key");
        String wx_app_secret = ConfigUtil.get("wx.app.secret");
        String tonglian_id = ConfigUtil.get("tonglian.id");
        String tonglian_key = ConfigUtil.get("tonglian.key");
        String tonglian_cusid = ConfigUtil.get("tonglian.cusid");
        String notify_url = ConfigUtil.get("wx.notify.url");
        form.setWx_app_secret(wx_app_secret);
        form.setWx_app_key(wx_app_key);
        form.setTonglian_id(tonglian_id);
        form.setTonglian_key(tonglian_key);
        form.setTonglian_cusid(tonglian_cusid);
        form.setNotify_url(notify_url);
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public HSBCPSBackVO funcBrokerAuthInfo(BrokerAuthSaveForm param) {
        zooKeeperConfigurator = null;
        try {
            String broker_id = param.getBroker_id();
            String wx_app_secret = param.getWx_app_secret();
            String wx_app_key = param.getWx_app_key();
            String tonglian_id = param.getTonglian_id();
            String tonglian_key = param.getTonglian_key();
            String tonglian_cusid = param.getTonglian_cusid();
            String notify_url = param.getNotify_url();
            zooKeeperConfigurator = ConfigUtil.getZkConfigurator();
            Map<String, Object> res = new HashMap<String, Object>();
            res.put("wx.app.secret", wx_app_secret);
            res.put("wx.app.key", wx_app_key);
            res.put("tonglian.id", tonglian_id);
            res.put("tonglian.key", tonglian_key);
            res.put("tonglian.cusid", tonglian_cusid);
            res.put("wx.notify.url", notify_url);
            Map<String, Object> resMap = new HashMap<String, Object>();
            resMap.put("auth.properties", res);
            zooKeeperConfigurator.getHSBCSConfigWriter("auth", broker_id).setConfiguration(resMap);
        } catch (Exception e) {
            logger.error("数据保存出错", e);
            return VOUtil.genErrorResult(SysMgtErr.SAVE_AUTH_INFO_FAIL, HSBCPSBackVO.class);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcSetInvitationCode(FansInvitationCodeForm form) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        chatRoom.setInvitation_code(form.getInvitation_code());
        chatRoomService.updateCAS(chatRoom);
        String key = CacheKeys.BROKER_RIGHT_INVITATION_CODE;
        CacheHelper cacheHelper = CacheHelper.getInstance();
        cacheHelper.hset(key, String.valueOf(broker_id), form.getInvitation_code());
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public FansInvitationCodeResult funcGetInvitationCode(HSBCPSVO form) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        FansInvitationCodeResult result = new FansInvitationCodeResult();
        result.setInvitation_code(chatRoom.getInvitation_code());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcHomePageTitleSet(HomePageTitleForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM, HomePageTitleResult.class);
        }
        chatRoom.setHome_page_title(param.getHome_page_title());
        chatRoomService.updateHomePageTitle(chatRoom);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HomePageTitleResult funcHomePageTitleGet(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, HomePageTitleResult.class);
        }
        String home_page_title = chatRoomService.getHomePageTitleByBrokerId(broker_id);
        
        HomePageTitleResult homePageTitleResult = new HomePageTitleResult();
        homePageTitleResult.setHome_page_title(home_page_title);
        
        return VOUtil.setSuccessResult(homePageTitleResult);
    }
    
    @Override
    public HSBCPSBackVO funcShowPersonNumSet(ShowPersonNumSetForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, HomePageTitleResult.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM, HomePageTitleResult.class);
        }
        chatRoom.setShow_person_num_threshold(ValueUtil.getInt(param.getShow_person_num_threshold(), 0));
        chatRoom.setShow_person_num_flag(param.getShow_person_num_flag());
        
        chatRoomService.updatePersonNumSetInfo(chatRoom);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public ConfigurableSystemSetInfoResult funcSystemSetInfoGet(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT,
                    ConfigurableSystemSetInfoResult.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM,
                    ConfigurableSystemSetInfoResult.class);
        }
        ConfigurableSystemSetInfoResult result = new ConfigurableSystemSetInfoResult();
        
        result.setHome_page_title(chatRoom.getHome_page_title());
        result.setShow_person_num_flag(chatRoom.getShow_person_num_flag());
        result.setShow_person_num_threshold(chatRoom.getShow_person_num_threshold());
        result.setSchemecolor_value(chatRoom.getSchemecolor_value());
        
        WechatShare wechatShare = wechatShareService.getWechatShareByBrokerId(broker_id);
        if (wechatShare != null) {
            result.setWechatshare_id(wechatShare.getWechatshare_id());
            result.setShare_abstract(wechatShare.getShare_abstract());
            result.setShare_title(wechatShare.getShare_title());
            result.setImg_url(wechatShare.getImg_url());
            result.setLink_url(wechatShare.getLink_url());
            result.setQrcode_url(wechatShare.getQrcode_url());
        }
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public ConfigurableSystemSetInfoResult funcSystemGetSkinInfo(BrokerTenantIdForm form) {
        Long broker_id = ValueUtil.getLong(form.getBroker_id());
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT,
                    ConfigurableSystemSetInfoResult.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM,
                    ConfigurableSystemSetInfoResult.class);
        }
        ConfigurableSystemSetInfoResult result = new ConfigurableSystemSetInfoResult();
        result.setSchemecolor_value(chatRoom.getSchemecolor_value());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcPaymentOptionSave(PaymentOptionSaveForm form) {
        Long broker_id = ValueUtil.getLong(form.getBroker_id());
        Integer tenant_id = ValueUtil.getInt(form.getTenant_id());
        //打赏选项
        String[] reward_option = form.getReward_option().split(",");
        //充值选项
        String[] recharge_option = form.getRecharge_option().split(",");
        List<PaymentOption> list = new ArrayList<PaymentOption>();
        try {
            for (int i = 0; i < recharge_option.length; i++) {
                PaymentOption pov = new PaymentOption();
                BigDecimal recharge = new BigDecimal(recharge_option[i]);
                int s = recharge.compareTo(new BigDecimal(0));
                if (1 != s) {
                    return VOUtil.genErrorResult(SysMgtErr.PAYMENT_AMOUNT_EXCEPTION, HSBCPSBackVO.class);
                }
                pov.setOption_type("1");
                pov.setBroker_id(broker_id);
                pov.setTenant_id(tenant_id);
                pov.setPayment_amount(recharge);
                list.add(pov);
            }
            for (int i = 0; i < reward_option.length; i++) {
                PaymentOption pov = new PaymentOption();
                BigDecimal reward = new BigDecimal(reward_option[i]);
                int s = reward.compareTo(new BigDecimal(0));
                if (1 != s) {
                    return VOUtil.genErrorResult(SysMgtErr.PAYMENT_AMOUNT_EXCEPTION, HSBCPSBackVO.class);
                }
                pov.setOption_type("2");
                pov.setBroker_id(broker_id);
                pov.setTenant_id(tenant_id);
                pov.setPayment_amount(new BigDecimal(reward_option[i]));
                list.add(pov);
            }
        } catch (Exception e) {
            return VOUtil.genErrorResult(SysMgtErr.PAYMENT_AMOUNT_EXCEPTION, HSBCPSBackVO.class);
        }
        //删除原有选项
        this.paymentOptionService.deleteByBrokerId(broker_id);
        //新增所有选项
        this.paymentOptionService.addAll(list);
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public PaymentOptionInfoForm funcPaymentOptionQry(BrokerIdForm form) {
        Long broker_id = form.getBroker_id();
        List<PaymentOption> list = this.paymentOptionService.getByBrokerId(broker_id);
        PaymentOptionInfoForm bol = new PaymentOptionInfoForm();
        StringBuilder recharge = new StringBuilder();
        StringBuilder reward = new StringBuilder();
        String recharge_option = null;
        String reward_option = null;
        if (null != list && list.size() > 0) {
            boolean flag = false;
            boolean flag1 = false;
            for (int i = 0; i < list.size(); i++) {
                PaymentOption po = list.get(i);
                if ("1".equals(po.getOption_type())) {
                    if (flag) {
                        recharge.append(",");
                    } else {
                        flag = true;
                    }
                    recharge.append(po.getPayment_amount());
                }
                if ("2".equals(po.getOption_type())) {
                    if (flag1) {
                        reward.append(",");
                    } else {
                        flag1 = true;
                    }
                    reward.append(po.getPayment_amount());
                }
            }
            recharge_option = recharge.toString();
            reward_option = reward.toString();
        } else {
            //获取默认配置
            recharge_option = ConfigUtil.get("recharge.option", DEFAULT_OPTION);
            reward_option = ConfigUtil.get("reward.option", DEFAULT_OPTION);
        }
        bol.setRecharge_option(recharge_option);
        bol.setReward_option(reward_option);
        return VOUtil.setSuccessResult(bol);
    }
    
    @Override
    public HSBCPSBackVO funcRefreshAccessToken(HSBCPSVO form) {
        AccessTokenUtil.refreshAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal());
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcAddOpinion(SuggestionAddForm form) {
        Feedback fd = new Feedback();
        fd.setCreate_time(new Date());
        fd.setFeedback_content(form.getSuggestion());
        fd.setSend_id(HSBCPSBizDataContext.getBrokerId());
        feedbackService.save(fd);
        return VOUtil.genSuccessResultVo();
    }
    
    //检测该租户下面是否已经有昵称，有返回true,没有返回false
    private boolean checkUserName(String name) {
        Integer total = brokerManagerService.checkUserName(name) + customerService.checkUserName(name);
        if (total > 0) {
            return true;
        }
        return false;
    }
    
}
